package com.mobilepay.moneypig.model.activity.launcher;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.config.Key;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.pro.UserInfo;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.PreferenceUtil;

import java.io.IOException;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

/**
 * Created by xlm on 2017/7/12 0012
 */

public class LauncherActivity extends BaseActivity {
    private static final String TAG = "LauncherActivity";
    private static final int PERMISSON_SOTRAGE = 0;
    String username;
    String pword;
    long startTime;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 3:
                    onLogin();
                    break;
                case 2:
                    finishActivity();
                    break;
            }
        }
    };

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_launcher);
    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void beforeSetContentView() {
        super.beforeSetContentView();
        setNavigationColor();
    }

    //设置导航栏透明
    private void setNavigationColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // Android 5.0 以上 全透明
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            // 虚拟导航键
            window.setNavigationBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // Android 4.4 以上 半透明
            Window window = getWindow();
            // 状态栏
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 虚拟导航键
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    GifImageView gifImageView;
    ImageView mImageViewCover;

    @Override
    protected void afterSetContentView() {
//        gifImageView = (GifImageView) findViewById(R.id.launcher_gif);
//        try {
//            GifDrawable gifDrawable = new GifDrawable(getResources(), R.mipmap.app_logo4);
//            gifImageView.setImageDrawable(gifDrawable);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        checkPermission();
    }

    @Override
    protected void onSetListener() {

    }

    /**
     * 检查权限，因为android6.0有些权限需要用户确认授权
     */

    private void checkPermission() {
        if (checkStoragePermission(PERMISSON_SOTRAGE)) {
            permissionOk();
        }
    }

    @Override
    public void onStoragePermission(int result_code, boolean result) {
        if (result) {
            checkPermission();
        } else {
            showToastShort("拒绝此权限，您将无法正常使用软件");
            finishActivityMillions(true, 2500);
        }
    }

    /**
     * 所有权限都已经获取
     */
    private void permissionOk() {
        username = (String) PreferenceUtil.getParam(getThis(), Key.USERNAME, "");
        pword = (String) PreferenceUtil.getParam(getThis(), Key.PASSWORD, "");
        if (!CommonUtil.isEmpty(username) && !CommonUtil.isEmpty(pword)) {
            if (App.getApp().isFirstUse()) {
                mHandler.sendEmptyMessageDelayed(2, 1300);
            } else {
                mHandler.sendEmptyMessage(3);
            }
        } else {
            mHandler.sendEmptyMessageDelayed(2, 1300);
        }
    }

    private void finishActivity() {
        startActivity(LoginActivity.class, true, false);
    }

    private boolean hasNet = true;

    //延迟1000ms
    private void delayTimeFinish(final boolean showToast, final String msg) {
        long loadingTime = System.currentTimeMillis() - startTime;
        if (loadingTime < 1300) {
            new Handler(getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (showToast) {
                        showToastShort(msg);
                    }
                    if (hasNet) {
                        startActivity(MainActivity.class, true, false);
                    } else
                        startActivity(LoginActivity.class, true, false);
                }
            }, 1300 - loadingTime);
        } else {
            if (showToast) {
                showToastShort(msg);
            }
            if (hasNet) {
                startActivity(MainActivity.class, true, false);
            } else
                startActivity(LoginActivity.class, true, false);
        }
    }

    /**
     * 登录
     */
    private void onLogin() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.login);
        param.add("username", username);
        param.add("password", pword);
        param.add("user_type", "2");
        param.add("sign", param.getMd5String());
        startTime = System.currentTimeMillis();
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                hasNet = false;
                delayTimeFinish(false, "");
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        UserInfo userInfo = GsonUtil.GsonToBean(string, UserInfo.class);
                        App.getApp().setUserInfo(userInfo);//保存用户信息
                        hasNet = true;
                        delayTimeFinish(false, "");
                    } else {
                        hasNet = false;
                        delayTimeFinish(true, responseResult.getInfo());
                    }
                } else {
                    hasNet = false;
                    delayTimeFinish(false, "");
                }
            }
        });
    }
}
